package com.tansun.easycare.rule.serialno.dao;

import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.tansun.easycare.rule.exception.BizException;
import com.tansun.rule.utils.StringUtils;

@Repository
public class RuleSerialNoDAO {

    @Autowired
    private DataSource dataSource;


    private JdbcTemplate jdbcTemplate;

    private DataSourceTransactionManager dsTxMgr;

    private final Log logger = LogFactory.getLog(RuleSerialNoDAO.class);


    public RuleSerialNoDAO() {
        init();
    }

    public void init() {
        if (dataSource != null) {
            jdbcTemplate = new JdbcTemplate(dataSource);
            dsTxMgr = new DataSourceTransactionManager(dataSource);
        }
    }

    public Long generateSerialNo(String key, String projectCode) throws BizException {
        if (jdbcTemplate == null) {
            init();
        }

        Long result = new Long(0);
        if (StringUtils.isEmpty(key) || StringUtils.isEmpty(projectCode)) {
            return result;
        }
        TransactionStatus txStatus = this.getTxStatus(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        try {
            StringBuffer sqlBuf = new StringBuffer();
            sqlBuf.append("select  serial_value  from  rule_serial_no  rs  where rs.Serial_KEY=? and  rs.project_code=?  for  update ");
            StringBuffer upBuf = new StringBuffer();
            List<Map<String, Object>> list = this.jdbcTemplate.queryForList(sqlBuf.toString(), key, projectCode);
            if (list != null && list.size() > 0) {
                Map<String, Object> map = list.get(0);
                String serial_value = map.get("serial_value").toString();
                if(serial_value.contains(".")) {
                	result = Long.valueOf(serial_value.split("\\.")[0]);
                }else {
                	result = Long.valueOf(serial_value);
                }
                
                result = result + 1;
                upBuf.append(" update   rule_serial_no     set  serial_value=?  where  Serial_KEY=?  and  project_code=?");
            } else {
                result = result + 1;
                upBuf.append(" insert into rule_serial_no (serial_value,Serial_KEY,project_code) VALUES (?,?,?)");
            }
            jdbcTemplate.update(upBuf.toString(), result, key, projectCode);
            dsTxMgr.commit(txStatus);

        } catch (Exception e) {
            dsTxMgr.rollback(txStatus);
            logger.info(e.getMessage(), e);
            throw new BizException(e, "");
        }
        return result;

    }


    private TransactionStatus getTxStatus(int txdefine) {

        DefaultTransactionDefinition txDef = getTxDef(txdefine);
        TransactionStatus txStatus = dsTxMgr.getTransaction(txDef);
        return txStatus;
    }

    private DefaultTransactionDefinition getTxDef(int txdefine) {
        DefaultTransactionDefinition dtDef = new DefaultTransactionDefinition();
        dtDef.setPropagationBehavior(txdefine);
        return dtDef;
    }


}
